<template>
  <div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="visible"
      v-if="visible"
      width="800px"
      :before-close="handleClose"
      center
      append-to-body
      ref="dialog"
    >
      <div class="jy-cydw-box" v-loading="loading">
        <slot>
          <el-row>
            <el-col :span="12" v-for="(item, index) in formConfig" :key="index">
              <el-checkbox
                v-model="formConfig[index]['value']"
                :disabled="formConfig[index].disabled"
                >{{ item.label }}</el-checkbox
              >
              <!-- <div
                v-if="
                  item.id == '1000000007' && item.value && action == 'modify'
                "
              >
                <el-tag
                  :key="tag"
                  v-for="tag in item.orgChildren"
                  :disable-transitions="false"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  width="120px"
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                  >+ 新增</el-button
                >
              </div> -->
              <!-- <div v-if="item.id == '1000000007' && action == 'view'">
                <el-tag
                  :key="tag"
                  v-for="tag in item.orgChildren"
                  :disable-transitions="true"
                >
                  {{ tag }}
                </el-tag>
              </div> -->

              <div v-if="item.id == '1000000007'">
                <tx-button-add name="预设置内设机构" @click="addYsjg(action)" />
              </div>
              <div
                v-if="
                  item.id == '1000000012' && item.value && action == 'modify'
                "
              >
                <el-cascader
                  v-model="item.children"
                  :options="typelist1"
                  :props="props"
                  collapse-tags
                  clearable
                  style="width: 330px"
                ></el-cascader>

                <!-- <el-select
                  v-model="item.children"
                  placeholder="请选择防护目标类型"
                  multiple
                  collapse-tags
                  style="width: 330px"
                >
                  <el-option
                    v-for="item in typelist1"
                    :key="item.value"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select> -->
                <!-- <el-select
                  v-model="item.children[1]"
                  placeholder="请选择二级防护目标类型"
                  multiple
                  collapse-tags
                  v-if="item.children[0]"
                >
                  <el-option
                    v-for="item in typelist2"
                    :key="item.value"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select> -->
              </div>
              <div v-if="item.id == '1000000012' && action == 'view'">
                <el-tag
                  :key="tag"
                  v-for="tag in item.childrenText"
                  :disable-transitions="true"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <div
                v-if="
                  item.id == '1000000014' && item.value && action == 'modify'
                "
              >
                <el-select
                  v-model="item.children"
                  placeholder="请选择避难场所类型"
                  multiple
                  collapse-tags
                  style="width: 330px"
                >
                  <el-option
                    v-for="item in typelist2"
                    :key="item.value"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </div>
              <div v-if="item.id == '1000000014' && action == 'view'">
                <el-tag
                  :key="tag"
                  v-for="tag in item.children"
                  :disable-transitions="true"
                >
                  {{ tag | tagText2 }}
                </el-tag>
              </div>
              <div
                v-if="
                  item.id == '1000002024' && item.value && action == 'modify'
                "
              >
                <el-cascader
                  v-model="item.children"
                  :options="typelist3"
                  :props="{
                    multiple: true,
                    expandTrigger: 'click',
                    value: 'id',
                    label: 'name',
                  }"
                  collapse-tags
                  clearable
                  style="width: 330px"
                  @change="handleChange"
                ></el-cascader>
              </div>
              <div v-if="item.id == '1000002024' && action == 'view'">
                <el-tag
                  :key="tag"
                  v-for="tag in item.childrenText"
                  :disable-transitions="true"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
        </slot>
      </div>
      <!-- <el-cascader :options="options" :props="props1" clearable></el-cascader> -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose()" :disabled="loading">取消</el-button>
        <el-button
          v-if="action == 'modify'"
          type="primary"
          @click="handleConfirm(row)"
          :disabled="loading"
          >确定</el-button
        >
      </div>
      <ysjg-list
        :ysjgData="formConfig[1]?.orgChildren"
        ref="ysjgList"
        @update="updateYsjg"
      />
    </el-dialog>
  </div>
</template>
<script>
let $that = this;
import YsjgList from "./ysjg-list.vue";
export default {
  components: { YsjgList },
  name: "ys-cydw",
  props: {
    label: {
      type: [String],
      default: "查看详情",
    },
    showKey: {
      type: [String],
      default: "",
    },
    field: {
      type: [String],
      default: "",
    },
    rules: {
      type: Object,
      default() {
        return {};
      },
    },
    content: {
      type: Object,
      default() {
        return {
          controller: null,
          props: {},
          columns: [],
        };
      },
    },
    row: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      selectedOptions: [],
      isFresh: false,
      dialogTitle: "",
      options: [
        {
          value: 1,
          label: "东南",
          children: [
            {
              value: 2,
              label: "上海",
            },
            {
              value: 7,
              label: "江苏",
              children: [
                { value: 8, label: "南京" },
                { value: 9, label: "苏州" },
                { value: 10, label: "无锡" },
              ],
            },
            {
              value: 12,
              label: "浙江",
              children: [
                { value: 13, label: "杭州" },
                { value: 14, label: "宁波" },
                { value: 15, label: "嘉兴" },
              ],
            },
          ],
        },
        {
          value: 17,
          label: "西北",
          children: [
            {
              value: 18,
              label: "陕西",
              children: [
                { value: 19, label: "西安" },
                { value: 20, label: "延安" },
              ],
            },
            {
              value: 21,
              label: "新疆维吾尔族自治区",
              children: [
                { value: 22, label: "乌鲁木齐" },
                { value: 23, label: "克拉玛依" },
              ],
            },
          ],
        },
      ],
      props1: { multiple: true },
      props: { multiple: true, label: "name", value: "id" },
      visible: false,
      labels: this.label,
      loading: false,
      formConfig: [],
      preFormConfig: [
        {
          prop: "type1",
          id: "1000000009",
          value: true,
          span: 12,
          disabled: true,
          component: "slot-type1",
          label: "单位领导",
        },
        {
          prop: "type2",
          id: "1000000007",
          value: true,
          span: 12,
          disabled: true,
          component: "slot-type2",
          label: "安全生产、防灾减灾内设机构",
          children: [],
          orgChildren: [],
        },
        {
          prop: "type3",
          id: "1000000008",
          value: false,
          span: 12,
          disabled: false,
          component: "slot-type3",
          label: "事业单位",
        },
        {
          prop: "type4",
          value: false,
          id: "1000000010",
          span: 12,
          disabled: false,
          component: "slot-type4",
          label: "救援队伍",
        },
        {
          prop: "type5",
          id: "1000000011",
          value: false,
          span: 12,
          disabled: false,
          component: "slot-type5",
          label: "应急物资",
        },
        {
          prop: "type6",
          id: "1000000012",
          value: false,
          span: 12,
          disabled: false,
          component: "slot-type6",
          label: "防护目标",
          children: [],
        },
        {
          prop: "type7",
          id: "1000000013",
          value: false,
          span: 12,
          disabled: false,
          component: "slot-type7",
          label: "专家库",
        },
        {
          prop: "type8",
          id: "1000000014",
          value: false,
          span: 12,
          disabled: false,
          component: "slot-type8",
          label: "避难场所",
        },
        {
          prop: "type9",
          id: "1000002024",
          value: false,
          span: 12,
          disabled: false,
          component: "slot-type9",
          label: "业务系统",
        },
      ],
      inputVisible: false,
      inputValue: "",
      typelist1: [], // 防护目标
      typelist2: [], // 避难场所
      typelist3: [], // 业务系统
      action: "view",
    };
  },
  // watch: {
  //   "formConfig[6].children[0]": function () {
  //     // 监听一级菜单触发二级菜单查询
  //     this.typelist2 = [];
  //     this.formConfig[6].children[1] = "";
  //     this.getOrgType(this.formConfig?.[6]?.children?.[1], "typelist2");
  //   },
  // },
  mounted() {
    this.getOrgType("1000000012", "typelist1");
    this.getOrgType("1000000014", "typelist2");
    this.getOrgType("1000002024", "typelist3");
  },
  computed: {
    menuId() {
      return this.getParameter("menuId") == "1000000010"; // 救援队伍
    },
  },
  beforeCreate: function () {
    $that = this;
  },
  filters: {
    tagText: function (val) {
      console.log($that.typelist1?.filter((i) => i.id == val)[0]);
      return $that.typelist1?.filter((i) => i.id == val)?.[0]?.["name"];
    },
    tagText2: function (val) {
      console.log($that.typelist2?.filter((i) => i.id == val)[0]);
      return $that.typelist2?.filter((i) => i.id == val)?.[0]?.["name"];
    },
  },
  methods: {
   
     isAllEqual(array) {
        if (array.length > 0) {
            return !array.some((value, index)=> {
                return value !== array[0];
            });
        } else {
            return true;
        }
    },
    handleChange(value) {
      // 处理选中值的变化
      // 如果没勾选
      if(value.length==0) {
        this.selectedOptions = [] // 存上一次勾选的第一级菜单为空
      }
      let newCheckboxArr = value.map((item)=>item[0]) // [[1,2],[3,4]]变成[1,3]一级数组
      if(!this.isAllEqual(newCheckboxArr)) { //是否有多个一级id存在，如果是则过滤
        let lastId = this.selectedOptions[0]; // 拿到上次勾选的一级数组id
        this.formConfig[8].children = value.filter((item)=>item[0]!=lastId) // 根据上次勾选的数组id过滤新勾选的一级数组。
        this.selectedOptions = [value.filter((item)=>item[0]!=lastId)[0][0]] // 新勾选的数组id保存起来
      }else {
        this.selectedOptions = newCheckboxArr;  // 新的第一次勾选的一级数组id保存
      }
      
    

      // 如果需要限制第一级只能单选，可以在这里进行判断和处理
      // if (value.length && value[0][0] === value[value.length - 1][0]) {
      //   // 如果第一级被多选了，则重置为第一个选中的值
      //   this.selectedOptions = value;
      //   console.log("Selected value1:", this.selectedOptions);
      // } else {
      //   this.selectedOptions.splice(this.selectedOptions.length - 1, 1);
      //   this.isFresh = !this.isFresh;
      //   this.$forceUpdate();
      // }
      // console.log("Selected value2:", this.selectedOptions);
    },
    changeYouHuiQuan(val) {
      let changeFlag = false;
      let changeItem = null;
      if (this.shareScopeEnd.length == 0) {
        this.youHuiQuanValue = val;
      } else {
        this.youHuiQuanValue.forEach((item) => {
          if (item[0] !== this.shareScopeEnd[0][0]) {
            changeFlag = true;
            changeItem = item;
          }
        });
      }
      if (changeFlag) {
        this.youHuiQuanValue = [];
        this.youHuiQuanValue.push(changeItem);
      }
      this.shareScopeEnd = this.youHuiQuanValue;
    },
    handleClick(scope, action) {
      this.dialogTitle = action == "view" ? "查看详情" : "编辑";
      this.formConfig = this.$lodash.cloneDeep(this.preFormConfig);
      this.action = action;
      let row = scope;
      if (!row || !row?.length) {
        if (action == "view") return false;
        else {
          this.visible = true;
        }
      } else {
        // this.label = '编辑';
        this.formConfig = this.formConfig.map((item) => {
          let items = row?.filter((i) => i.id == item.id)[0];
          return {
            ...item,
            value: !!(
              (items?.id || item.id == "1000000007")
              // || item.id == "1000000012"
            ),
            children:
              item.id == "1000000014"
                ? items?.children.flat()
                : items?.children || [],
            orgChildren: items?.orgChildren || [],
            childrenText: items?.childrenText || [],
            disabled: !!(
              (action == "view" || item.id == "1000000007")
              // || item.id == "1000000012"
            ),
          };
        });
        console.log("this.formConfig", this.formConfig);
        this.visible = true;
        this.selectedOptions = [this.formConfig[8].children[0][0]] // 查询数据库保存的只会有一个一级数组id，保存本地，用于后续的勾选修改做判断使用
      }

      console.log("this.formConfig", this.formConfig);
    },
    change(changeVal, type) {
      console.log(this.oneId);
      // 当前改变的值、当前编辑的行、当前row中的key、当前下拉框的list数组值
      // 选择下拉
    },
    handleTagsClose(tag) {
      this.formConfig[1].orgChildren.splice(
        this.formConfig[1].orgChildren.indexOf(tag),
        1
      );
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput[0].$el.querySelector("input").focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.formConfig[1].orgChildren.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    handleConfirm() {
      // if (this.formConfig[1].value&&this.formConfig[1]?.orgChildren?.length < 1) {
      //   this.$message.error("预设机构不能为空");
      //   return false;
      // }
      if (
        this.formConfig[5].value &&
        this.formConfig[5]?.children?.length < 1
      ) {
        this.$message.error("请选择防护目标类型");
        return false;
      }
      if (
        this.formConfig[7].value &&
        this.formConfig[7]?.children?.length < 1
      ) {
        this.$message.error("请选择避难场所类型");
        return false;
      } else {
        if (this.formConfig[7].value) {
          let data = this.formConfig[7]?.children.map((item) => {
            return [item];
          });
          this.formConfig[7].children = [...data];
        }
      }
      if (
        this.formConfig[8]?.children?.length < 1
      ) {
        this.$message.error("请选择业务系统");
        return false;
      }
      let confirmData = this.formConfig
        .filter((i) => i.value)
        .map((item) => {
          return {
            id: item.id,
            label: item.label,
            children: item.children || [],
            orgChildren: item.orgChildren || [],
          };
        });
      this.$emit("update", confirmData);
      // row = this.$lodash.cloneDeep(this.editRow);
      // row.sourceType = this.editRow.sourceType;
      this.visible = false;
      // console.log("this.editRow", this.editRow);
    },
    handleClose(row) {
      // row = this.editRow;
      // row.sourceType = row.$sourceType;
      // row.sourceTypeValue = row.$sourceTypeValue;
      // this.oneId = "";
      // this.twoId = this.menuId ? [] : "";
      this.visible = false;
    },
    updateYsjg(res) {
      this.formConfig[1].orgChildren = res;
    },
    getOrgType(parId, typelist) {
      if (!parId) {
        return false;
      }
      // 获取类型列表
      let data = {
        body: {
          parId,
        },
      };
      this.$api.OrgController.type(data, (res) => {
        if (res.code == 0) {
          this[typelist] = res?.data;
        }
      });
    },
    changeOrgType(val) {
      this.formConfig[6].children[0] = val;
    },
    addYsjg(action) {
      this.$refs.ysjgList.open(action);
    },
  },
};
</script>

<style lang="scss" scope>
.el-checkbox-group {
  div {
    margin: 3px 0;
  }
}
.tx-list-table .el-table .el-tooltip .cell-text {
  margin-bottom: 12px;
}

.el-row .el-col > label {
  text-align: left;
}

.el-tag {
  margin-right: 10px;
  margin-bottom: 3px;
}
.button-new-tag {
  // margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  // margin-left: 10px;
  vertical-align: bottom;
}

.el-scrollbar__wrap {
  max-height: 520px;
  height: auto;
}
</style>
